package com.lineage.data.item_etcitem.doll;

import java.lang.reflect.Field;
import java.nio.channels.Pipe.SourceChannel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.lineage.DatabaseFactory;
import com.lineage.data.cmd.CreateNewItem;
import com.lineage.data.executor.ItemExecutor;
import com.lineage.server.datatables.DollPowerTable;
import com.lineage.server.datatables.ItemPowerUpdateTable;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.datatables.SupperDollTable;
import com.lineage.server.model.L1Object;
import com.lineage.server.model.Instance.L1DollInstance;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.doll.L1DollExecutor;
import com.lineage.server.model.doll.L1DollPowerSupper;
import com.lineage.server.model.item.L1ItemId;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.templates.L1Doll;
import com.lineage.server.templates.L1Item;
import com.lineage.server.templates.L1ItemPowerUpdate;
import com.lineage.server.templates.L1SupperDoll;
import com.lineage.server.utils.SQLUtil;
import com.lineage.server.world.World;
import com.lineage.server.world.WorldItem;
import com.mchange.v2.codegen.bean.BeangenUtils;



/**
 * 60219 魔法娃娃重生药剂
 * 随机生成魔法娃娃的技能
 * 
 */

public class DollReborn extends ItemExecutor{
	private static final Log _log = LogFactory.getLog(DollReborn.class);

	private   HashMap<Integer, L1DollExecutor> _classList;
	


//	private static final ArrayList<String> _checkList = new ArrayList<String>();
	private static final Random _random = new Random();


	public static DollReborn get() {
		return new DollReborn();
	}
	
	
	@Override
	public void execute(final int[] data, final L1PcInstance pc,
			final L1ItemInstance item) {
		try {
			// 对像OBJID
			final int targObjId = data[0];

			final L1ItemInstance tgItem = pc.getInventory().getItem(targObjId);

			if (tgItem == null) {
				return;
			}
			
			_classList = SupperDollTable.get().get_classList();

			//基础属性都来自基础属性表，所以可以从这个表里，根据itemid来匹配
			final L1Doll doll = DollPowerTable.get().get_type(tgItem.getItemId());
//			final L1SupperDoll doll1 = SupperDollTable.get().get_type(tgItem.getItemId());
			if (doll == null ) {
				// 2,477：只有魔法娃娃可以选择。
				pc.sendPackets(new S_ServerMessage(2477));
				return;
			}

			if (pc.getDoll(tgItem.getId()) != null) {
				// 1,181：这个魔法娃娃目前正在使用中。
				pc.sendPackets(new S_ServerMessage(1181));
				return;
			}
			if (pc.getDoll2(tgItem.getId()) != null) {
				// 1,181：这个魔法娃娃目前正在使用中。
				pc.sendPackets(new S_ServerMessage(1181));
				return;
			}
			
			// 删除卷轴
			pc.getInventory().removeItem(item, 1);
			
			
			
			


			L1SupperDoll supperDoll = new L1SupperDoll();
			Field[] sourceFields = doll.getClass().getDeclaredFields();
			Field[] targetFields = supperDoll.getClass().getDeclaredFields();
			for (Field sourceField : sourceFields) {
			    for (Field targetField : targetFields) {
			        if (sourceField.getName().equals(targetField.getName()) 
			            && sourceField.getType() == targetField.getType()) {
			            sourceField.setAccessible(true);
			            targetField.setAccessible(true);
			            targetField.set(supperDoll, sourceField.get(doll));
			        }
			    }
			}

			
			//第一只超级娃娃
						
			if (SupperDollTable.get().get_powerMap().keySet().isEmpty()) {

				pc.getInventory().removeItem(tgItem,1);
		        WorldItem.get().remove(tgItem.getId());		        
				L1ItemInstance new_item = ItemTable.get().createItem(tgItem.getItemId());
		        String s = newPowerList() ;
				SupperDollTable.get().runInsert(tgItem.getId(),new_item.getItemId(), pc, s, supperDoll.get_gfxid(), supperDoll.get_nameid());
//		        //超级娃娃每个娃娃对应一个type，所以新生成的娃娃需要新生成一个对应的type，而不是从初始化的列表里面去取，所以西面的写法是错误的。
//		        L1SupperDoll supperDoll = SupperDollTable.get().get_type(new_item.getId());
		        
//		        L1SupperDoll supperDoll = new L1SupperDoll();
		        supperDoll.setPowerList(StringToPowerList(s));
		        SupperDollTable.get().get_powerMap().put(new_item.getId(), supperDoll);
				if (new_item != null) {
					new_item.setIdentified(true);
					new_item.setCount(1);
					pc.getInventory().storeItem(new_item);
				}
				
			} else{
				int supperid = 0;
				Set<Integer> keyset = SupperDollTable.get().get_powerMap().keySet();
				Iterator<Integer> iterator = keyset.iterator();
				while (iterator.hasNext()) {
				    Integer key = iterator.next();
				    if ((int) key == tgItem.getId()) {
				    	supperid = (int)key;
				    	break;
				    	}
				    }
				if (supperid > 0 ) {

			        pc.getInventory().removeItem(tgItem);
			        WorldItem.get().remove(supperid);
			        SupperDollTable.get().get_powerMap().remove(supperid);
			        L1ItemInstance new_item = ItemTable.get().createItem(tgItem.getItemId());
			        String s = newPowerList() ;
			        SupperDollTable.get().update(supperid,new_item.getId(), s );
//			        //超级娃娃每个娃娃对应一个type，所以新生成的娃娃需要新生成一个对应的type，而不是从初始化的列表里面去取，所以西面的写法是错误的。
//			        L1SupperDoll supperDoll = SupperDollTable.get().get_type(new_item.getId());
			        
//			        L1SupperDoll supperDoll = new L1SupperDoll();
			        supperDoll.setPowerList(StringToPowerList(s));
			        SupperDollTable.get().get_powerMap().put(new_item.getId(), supperDoll);

			        if (new_item != null) {
			            new_item.setIdentified(true);
			            new_item.setCount(1);
			            pc.getInventory().storeItem(new_item);
					}
				}else {
					pc.getInventory().removeItem(tgItem,1);	
					WorldItem.get().remove(Integer.valueOf(tgItem.getId())  );		
					L1ItemInstance new_item = ItemTable.get().createItem(tgItem.getItemId());
			        String s = newPowerList() ;
					SupperDollTable.get().runInsert(new_item.getId(),new_item.getItemId(), pc, s, supperDoll.get_gfxid(), supperDoll.get_nameid());
//			        //超级娃娃每个娃娃对应一个type，所以新生成的娃娃需要新生成一个对应的type，而不是从初始化的列表里面去取，所以西面的写法是错误的。
//			        L1SupperDoll supperDoll = SupperDollTable.get().get_type(new_item.getId());
			        //这里new 一个supperDoll的话，supperdoll的各项都是空的，需要从L1Doll魔板里面拿。
					
//			        L1SupperDoll supperDoll = new L1SupperDoll();
			        supperDoll.setPowerList(StringToPowerList(s));
			        SupperDollTable.get().get_powerMap().put(new_item.getId(), supperDoll);
					if (new_item != null) {
						new_item.setIdentified(true);
						new_item.setCount(1);
						Integer integer = new_item.getId();
						pc.getInventory().storeItem(new_item);
					}
				}


			}


			

//			// 产生新物件			
//			final L1ItemInstance tginfo_item = ItemTable.get().createItem(tgItem.getItemId());
//			final L1Doll dollnew = DollPowerTable.get().get_type(tginfo_item.getItemId());
//			int newTargObjId = tginfo_item.getId();
//			reSetPowers(dollnew, newTargObjId, targObjId);
//			if (tginfo_item != null) {
//				tginfo_item.setIdentified(true);
//				tginfo_item.setCount(1);
//				pc.getInventory().storeItem(tginfo_item);
//			}


			
			//试试看用checkItem能不能刷新
//			final L1Doll dollnew = doll;
//			
//			int newTargObjId = targObjId;
//			
//			reSetPowers(dollnew, newTargObjId, targObjId);
//			
//			pc.getInventory().checkItem(newTargObjId);
//			pc.getInventory().

			

			     
		


		} catch (final Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		}
	}
	
	public String newPowerList() {
		int powerCount = _random.nextInt(6) + 3;
		String [] dollPowerSet1 = new String[powerCount];
		try {
			 // 生成一个3到8的随机整数
			dollPowerSet1 = new String[powerCount];
			for (int i =0; i<dollPowerSet1.length; i++ ) {

					dollPowerSet1[i] = "" + ( _random.nextInt(393) + 1 );

			}
			
		} catch (Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		}
		
		String s = "";
		for (String string : dollPowerSet1) {
			s = string + "," + s;
		}
		
		return s;
	}
	
	  
	public ArrayList<L1DollExecutor>  StringToPowerList(String s){
	String dollPowers = s.replaceAll(" ", "");	
	ArrayList<L1DollExecutor> powerList = new ArrayList<L1DollExecutor>();
	if ((dollPowers != null) && (!dollPowers.equals(""))) {
		String[] dollPowerSet1 = dollPowers.split(",");
		for (String string : dollPowerSet1) {

			L1DollExecutor e =  (L1DollExecutor) _classList.get(Integer.valueOf(Integer.parseInt(string)));
			if (e != null) {
				//这里添加娃娃的能力值
				powerList.add(e);
			} else {
				_log.error("娃娃能力读取错误-没有这个编号:" + string);
			}
		}
		}
	return powerList;
	}
	

	
	
//	public void reSetPowers(L1Doll dollnew,final int targObjId ) {
//		L1Doll powerDoll = dollnew;
//		try {
//			
//			int powerCount = _random.nextInt(6) + 3; // 生成一个3到8的随机整数
//			String [] dollPowerSet1 = new String[powerCount];
//			for (int i =0; i<dollPowerSet1.length; i++ ) {
//				// 取一个数据库etcitem_doll_power中id的最大值，并取其中的随机值，由于有空缺，所以需要判断取出的ID是否可以用
////				int tmp = _random.nextInt(393) + 1 ;
//				//判断这个id是否存在于表中
////				if(DollPowerTable.get().get_classList().containsValue(tmp)){
//					dollPowerSet1[i] = "" + ( _random.nextInt(393) + 1 );
////				}
//			}
//			boolean iserr = false;
//			ArrayList<L1DollExecutor> powerList = new ArrayList<L1DollExecutor>();
//			if ( dollPowerSet1.length > 0 ) {
//				for (String string : dollPowerSet1) {
//					L1DollExecutor e = (L1DollExecutor) _classList.get(Integer.valueOf(Integer.parseInt(string)));
//
//					if (e != null) {
//						//这里添加娃娃的能力值						
//						//处理相同属性的能力值重复的问题				
//						powerList.add(e);
//						
//					} else {
//						_log.error("娃娃能力取回错误-没有这个编号,是这里么:" + string);
//						iserr = true;
//					}
//				}
//			}
//			powerDoll.setPowerList(powerList);	
//
//		} catch (Exception e) {
//			_log.error(e.getLocalizedMessage(), e);
//		}
//	}
//	
//
//
//
//	
//	public void writeDPStable(int newTargetId, final int targObjId,  String [] dollPowerSet ) {
//		
//		String [] dollPowerSet2 = dollPowerSet;
//		String s = "";
//		for (String string : dollPowerSet2) {
//			s = string + "," + s;
//		}
//		
//		runInsert(newTargetId, s);
//		
//		runDelete(targObjId);
//	}
//	
//	private void runUpdate(final int targObjId, String s) {
//		Connection cn = null;
//		PreparedStatement ps = null;
//		try {
//			cn = DatabaseFactory.get().getConnection();
//			ps = cn.prepareStatement("UPDATE `doll_power_supper` SET powers=? WHERE `id`=?");
//			ps.setString(1, s);
//			ps.setInt(2, targObjId);
//			ps.execute();
//		} catch (Exception e) {
//			_log.error(e.getLocalizedMessage(), e);
//		} finally {
//			SQLUtil.close(ps);
//			SQLUtil.close(cn);
//		}
//	}
//	
//	private void runInsert(final int newTargetId, String s) {
//		Connection cn = null;
//		PreparedStatement ps = null;
//		try {
//			cn = DatabaseFactory.get().getConnection();
//			ps = cn.prepareStatement("INSERT INTO `doll_power_supper` SET id=?, powers =?");
//			ps.setInt(1, newTargetId);
//			ps.setString(2, s);
//			ps.execute();
//		} catch (Exception e) {
//			_log.error(e.getLocalizedMessage(), e);
//		} finally {
//			SQLUtil.close(ps);
//			SQLUtil.close(cn);
//
//		}
//	}
//	
//	private void runDelete(final int targObjId) {
//		Connection cn = null;
//		PreparedStatement ps = null;
//		try {
//			cn = DatabaseFactory.get().getConnection();
//			ps = cn.prepareStatement("Delete from `doll_power_supper` WHERE `id`=?");
//			ps.setInt(1, targObjId);
//			ps.execute();
//		} catch (Exception e) {
//			_log.error(e.getLocalizedMessage(), e);
//		} finally {
//			SQLUtil.close(ps);
//			SQLUtil.close(cn);
//
//		}
//	}
//


//	@Override
//	public void execute(L1PcInstance pc) {
//		// TODO Auto-generated method stub
//		
//	}
//
//
//
//	@Override
//	public void execute(L1PcInstance pc, L1ItemInstance item) {
//		// TODO Auto-generated method stub
//		
//	}
}

